const Koa = require("koa");
const bodyParser = require("koa-bodyparser");
const cors = require("@koa/cors");
const sqlite3 = require("sqlite3").verbose();
const os = require("os");

const indexRoutes = require("./routes/index");

const db = new sqlite3.Database("./mlite.db", (err) => {
  if (err) {
    console.error("Failed to open database:", err.message);
  } else {
    console.log("Connected to the SQLite database.");
  }
});

const app = new Koa();
app.proxy = true;
app.context.db = db;

app.use(cors());
app.use(bodyParser());

app.use(indexRoutes.routes()).use(indexRoutes.allowedMethods());

const PORT = 7000;
const HOST = "0.0.0.0";

// 获取本机 IP 地址
function getLocalIPAddress() {
  const interfaces = os.networkInterfaces();
  for (const iface of Object.values(interfaces)) {
    for (const alias of iface) {
      if (alias.family === "IPv4" && !alias.internal) {
        return alias.address;
      }
    }
  }
  return "127.0.0.1";
}

app.listen(PORT, HOST, () => {
  const localIP = getLocalIPAddress();
  console.log(`Server is running on http://${localIP}:${PORT}`);
});
